using System;
using System.Net.NetworkInformation;
using System.Net;
using System.Diagnostics;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Linq;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Text;

namespace NetworkConfigApp
{
    public partial class MasterForm : Form
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);

        [Flags]
        private enum EXECUTION_STATE : uint
        {
            ES_AWAYMODE_REQUIRED = 0x00000040,
            ES_CONTINUOUS = 0x80000000,
            ES_DISPLAY_REQUIRED = 0x00000002,
            ES_SYSTEM_REQUIRED = 0x00000001
        }

        private bool isInitializing = true;
        private string originalIP = string.Empty;
        private string originalGateway = string.Empty;
        private string originalSubnetMask = string.Empty;
        private string originalPrimaryDNS = string.Empty;
        private string originalSecondaryDNS = string.Empty;
        private bool isSleepPrevented = false;
        private string originalStandbyTimeout = "30"; // 默认值
        private string originalMonitorTimeout = "15"; // 默认值
        private Point lastPoint;
        private System.Windows.Forms.Timer animationTimer;
        private float glowOpacity = 0f;
        private bool isGlowing = false;
        private System.Windows.Forms.Timer keepAliveTimer;
        private List<NetworkAdapterInfo> cachedAdapters;
        private DateTime lastLoadTime = DateTime.MinValue;
        private const int CACHE_DURATION_SECONDS = 5;
        private SplashForm splashForm;
        private ProgressForm progressForm;

        public MasterForm()
        {
            // 显示启动画面
            splashForm = new SplashForm();
            splashForm.Show();
            Application.DoEvents();

            // 只执行最基本的初始化
            InitializeComponent();
            isInitializing = true;

            // 设置窗体加载事件
            this.Load += MasterForm_Load;
            this.Shown += MasterForm_Shown;
        }

        private void InitializeAnimations()
        {
            if (animationTimer == null)
            {
                animationTimer = new System.Windows.Forms.Timer();
                animationTimer.Interval = 16; // 约60fps
                animationTimer.Tick += AnimationTimer_Tick;
            }
        }

        private void AnimationTimer_Tick(object sender, EventArgs e)
        {
            if (isGlowing)
            {
                glowOpacity += 0.1f;
                if (glowOpacity >= 1f)
                {
                    glowOpacity = 1f;
                    isGlowing = false;
                }
            }
            else
            {
                glowOpacity -= 0.1f;
                if (glowOpacity <= 0f)
                {
                    glowOpacity = 0f;
                    animationTimer.Stop();
                }
            }
            this.Invalidate();
        }

        private void MasterForm_Paint(object sender, PaintEventArgs e)
        {
            // 创建圆角矩形路径
            using (GraphicsPath path = new GraphicsPath())
            {
                int radius = 10;
                Rectangle rect = new Rectangle(0, 0, this.Width - 1, this.Height - 1);
                path.AddArc(rect.X, rect.Y, radius * 2, radius * 2, 180, 90);
                path.AddArc(rect.Right - radius * 2, rect.Y, radius * 2, radius * 2, 270, 90);
                path.AddArc(rect.Right - radius * 2, rect.Bottom - radius * 2, radius * 2, radius * 2, 0, 90);
                path.AddArc(rect.X, rect.Bottom - radius * 2, radius * 2, radius * 2, 90, 90);
                path.CloseAllFigures();

                // 设置窗体区域
                this.Region = new Region(path);

                // 绘制发光效果
                if (glowOpacity > 0)
                {
                    using (Pen glowPen = new Pen(Color.FromArgb((int)(glowOpacity * 255), 0, 122, 204), 2))
                    {
                        e.Graphics.DrawPath(glowPen, path);
                    }
                }

                // 绘制渐变背景
                using (LinearGradientBrush brush = new LinearGradientBrush(
                    rect,
                    Color.FromArgb(30, 30, 30),
                    Color.FromArgb(45, 45, 48),
                    LinearGradientMode.Vertical))
                {
                    e.Graphics.FillPath(brush, path);
                }
            }
        }

        private void InitializeCustomButtons()
        {
            if (btnMinimize == null || btnClose == null || btnSave == null) return;

            // 设置按钮样式
            btnMinimize.FlatAppearance.BorderSize = 0;
            btnMinimize.FlatStyle = FlatStyle.Flat;
            btnMinimize.BackColor = Color.FromArgb(35, 35, 38);
            btnMinimize.Cursor = Cursors.Hand;
            btnMinimize.Text = "─";
            btnMinimize.Font = new Font("微软雅黑", 12, FontStyle.Bold);

            btnClose.FlatAppearance.BorderSize = 0;
            btnClose.FlatStyle = FlatStyle.Flat;
            btnClose.BackColor = Color.FromArgb(35, 35, 38);
            btnClose.Cursor = Cursors.Hand;
            btnClose.Text = "×";
            btnClose.Font = new Font("微软雅黑", 12, FontStyle.Bold);

            // 设置按钮悬停效果
            btnMinimize.MouseEnter += (s, e) =>
            {
                if (btnMinimize != null)
                {
                    btnMinimize.BackColor = Color.FromArgb(232, 17, 35);
                    btnMinimize.ForeColor = Color.White;
                }
            };
            btnMinimize.MouseLeave += (s, e) =>
            {
                if (btnMinimize != null)
                {
                    btnMinimize.BackColor = Color.FromArgb(35, 35, 38);
                    btnMinimize.ForeColor = Color.White;
                }
            };
            btnClose.MouseEnter += (s, e) =>
            {
                if (btnClose != null)
                {
                    btnClose.BackColor = Color.FromArgb(232, 17, 35);
                    btnClose.ForeColor = Color.White;
                }
            };
            btnClose.MouseLeave += (s, e) =>
            {
                if (btnClose != null)
                {
                    btnClose.BackColor = Color.FromArgb(35, 35, 38);
                    btnClose.ForeColor = Color.White;
                }
            };

            // 设置保存按钮效果
            btnSave.MouseEnter += (s, e) =>
            {
                if (btnSave != null)
                {
                    btnSave.BackColor = Color.FromArgb(0, 102, 184);
                    isGlowing = true;
                    if (animationTimer != null)
                    {
                        animationTimer.Start();
                    }
                }
            };
            btnSave.MouseLeave += (s, e) =>
            {
                if (btnSave != null)
                {
                    btnSave.BackColor = Color.FromArgb(0, 122, 204);
                    isGlowing = false;
                }
            };

            // 设置输入框效果
            foreach (Control control in this.Controls)
            {
                if (control is TextBox || control is ComboBox)
                {
                    control.Paint += (s, e) =>
                    {
                        if (s is TextBox || s is ComboBox)
                        {
                            using (Pen pen = new Pen(Color.FromArgb(0, 192, 192), 1))
                            {
                                e.Graphics.DrawRectangle(pen, new Rectangle(0, 0, control.Width - 1, control.Height - 1));
                            }
                        }
                    };
                }
            }
        }

        // 最小化按钮点击事件
        private void btnMinimize_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            this.ShowInTaskbar = true;
            this.Hide();
            this.Show();
        }

        // 关闭按钮点击事件
        private void btnClose_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        // 窗体拖动相关事件
        private void MasterForm_MouseDown(object sender, MouseEventArgs e)
        {
            lastPoint = new Point(e.X, e.Y);
        }

        private void MasterForm_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Left += e.X - lastPoint.X;
                this.Top += e.Y - lastPoint.Y;
            }
        }

        private void MasterForm_MouseUp(object sender, MouseEventArgs e)
        {
            lastPoint = Point.Empty;
        }

        // 添加一个辅助方法来安全地执行UI操作
        private void SafeInvoke(Action action)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(action);
            }
            else
            {
                action();
            }
        }

        private void MasterForm_Load(object sender, EventArgs e)
        {
            // 在后台线程中执行非UI初始化
            Task.Run(() =>
            {
                try
                {
                    // 在主线程中执行UI初始化
                    SafeInvoke(() =>
                    {
                        splashForm.UpdateStatus("正在初始化界面...");
                        InitializeCustomButtons();
                        InitializeAnimations();
                        this.Paint += MasterForm_Paint;
                    });

                    // 预加载网络适配器信息
                    SafeInvoke(() => splashForm.UpdateStatus("正在加载网络适配器..."));
                    LoadNetworkAdapters(true); // 强制刷新

                    // 预加载网络设置
                    SafeInvoke(() => splashForm.UpdateStatus("正在加载网络设置..."));
                    LoadCurrentNetworkSettings();

                    // 检查休眠状态
                    SafeInvoke(() => splashForm.UpdateStatus("正在检查系统状态..."));
                    CheckCurrentSleepState();

                    // 在主线程中完成初始化
                    SafeInvoke(() =>
                    {
                        InitializeKeepAliveTimer();

                        if (isSleepPrevented)
                        {
                            SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS |
                                                  EXECUTION_STATE.ES_SYSTEM_REQUIRED |
                                                  EXECUTION_STATE.ES_DISPLAY_REQUIRED);
                            keepAliveTimer.Start();
                        }

                        // 关闭启动画面
                        if (splashForm != null && !splashForm.IsDisposed)
                        {
                            splashForm.Close();
                            splashForm.Dispose();
                            splashForm = null;
                        }
                    });
                }
                catch (Exception ex)
                {
                    SafeInvoke(() =>
                    {
                        if (splashForm != null && !splashForm.IsDisposed)
                        {
                            splashForm.Close();
                            splashForm.Dispose();
                            splashForm = null;
                        }
                        MessageBox.Show($"初始化过程中出错：{ex.Message}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    });
                }
                finally
                {
                    SafeInvoke(() => isInitializing = false);
                }
            });
        }

        private void MasterForm_Shown(object sender, EventArgs e)
        {
            // 窗体显示后，确保启动画面在最前面
            if (splashForm != null && !splashForm.IsDisposed)
            {
                splashForm.BringToFront();
            }
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            // 确保启动画面被关闭
            if (splashForm != null && !splashForm.IsDisposed)
            {
                splashForm.Close();
                splashForm.Dispose();
                splashForm = null;
            }
        }

        // 加载网络适配器列表
        private void LoadNetworkAdapters(bool forceRefresh = false)
        {
            try
            {
                // 检查缓存是否有效
                if (!forceRefresh && cachedAdapters != null &&
                    (DateTime.Now - lastLoadTime).TotalSeconds < CACHE_DURATION_SECONDS)
                {
                    SafeInvoke(() =>
                    {
                        comboBoxAdapters.DisplayMember = "Name";
                        comboBoxAdapters.ValueMember = "Name";
                        comboBoxAdapters.DataSource = null;
                        comboBoxAdapters.DataSource = cachedAdapters;
                        if (cachedAdapters.Count > 0)
                        {
                            comboBoxAdapters.SelectedIndex = cachedAdapters.FindLastIndex(n => !string.IsNullOrWhiteSpace(n.Gateway));
                        }
                    });
                    return;
                }

                var adapterList = new List<NetworkAdapterInfo>();
                var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces()
                    .Where(n => n.OperationalStatus == OperationalStatus.Up &&
                          (n.NetworkInterfaceType == NetworkInterfaceType.Ethernet ||
                           n.NetworkInterfaceType == NetworkInterfaceType.Wireless80211));

                foreach (var item in networkInterfaces)
                {
                    try
                    {
                        string ipAddress = "";
                        string gateway = "";
                        var ipProps = item.GetIPProperties();

                        // 获取IPv4地址
                        var ipv4 = ipProps.UnicastAddresses
                            .FirstOrDefault(addr => addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
                        if (ipv4 != null)
                        {
                            ipAddress = ipv4.Address.ToString();
                        }

                        // 获取网关地址
                        var gw = ipProps.GatewayAddresses
                            .FirstOrDefault(g => g.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
                        if (gw != null)
                        {
                            gateway = gw.Address.ToString();
                        }

                        // 获取DHCP状态
                        bool isDHCPEnabled = false;
                        bool isDNSDHCPEnabled = false;
                        try
                        {
                            var process = new Process
                            {
                                StartInfo = new ProcessStartInfo
                                {
                                    FileName = "netsh",
                                    Arguments = $"interface ip show config \"{item.Name}\"",
                                    UseShellExecute = false,
                                    RedirectStandardOutput = true,
                                    CreateNoWindow = true
                                }
                            };
                            process.Start();
                            string output = process.StandardOutput.ReadToEnd();
                            process.WaitForExit();

                            if (Regex.IsMatch(output, @"DHCP\s+enabled:\s*Yes"))
                            {
                                isDHCPEnabled = true;
                            }
                            else if (Regex.IsMatch(output, @"DHCP\s+已启用:\s*是"))
                            {
                                isDHCPEnabled = true;
                            }
                            if (Regex.IsMatch(output, @"DNS servers configured through\s+\DHCP:\s*Yes"))
                            {
                                isDNSDHCPEnabled = true;
                            }
                            else
                            {
                                isDNSDHCPEnabled = !output.Contains("静态配置的");
                            }
                        }
                        catch { }

                        var adapterInfo = new NetworkAdapterInfo
                        {
                            Name = item.Name,
                            Description = item.Description,
                            IPAddress = ipAddress,
                            Gateway = gateway,
                            IsDHCPEnabled = isDHCPEnabled,
                            IsDNSDHCPEnabled = isDNSDHCPEnabled
                        };
                        adapterList.Add(adapterInfo);
                    }
                    catch { /* 忽略单个适配器的错误，继续处理其他适配器 */ }
                }

                // 更新缓存
                cachedAdapters = adapterList;
                lastLoadTime = DateTime.Now;

                // 在主线程中更新UI
                SafeInvoke(() =>
                {
                    try
                    {
                        comboBoxAdapters.DisplayMember = "Name";
                        comboBoxAdapters.ValueMember = "Name";
                        comboBoxAdapters.DataSource = null;
                        comboBoxAdapters.DataSource = adapterList;
                        if (adapterList.Count > 0)
                        {
                            comboBoxAdapters.SelectedIndex = adapterList.FindLastIndex(n => !string.IsNullOrWhiteSpace(n.Gateway));
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"更新网络适配器列表时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                });
            }
            catch (Exception ex)
            {
                SafeInvoke(() =>
                {
                    MessageBox.Show($"加载网络适配器时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                });
            }
        }

        // 适配器信息类
        public class NetworkAdapterInfo
        {
            public string Name { get; set; }
            public string Description { get; set; }
            public string IPAddress { get; set; }
            public string Gateway { get; set; }
            public bool IsDHCPEnabled { get; set; }
            public bool IsDNSDHCPEnabled { get; set; }
            public override string ToString() => $"{Name} ({IPAddress})";
        }

        // 添加进度条窗体类
        private class ProgressForm : Form
        {
            private ProgressBar progressBar;
            private Label statusLabel;

            public ProgressForm()
            {
                this.Size = new Size(400, 150);
                this.FormBorderStyle = FormBorderStyle.None;
                this.StartPosition = FormStartPosition.CenterParent;
                this.BackColor = Color.FromArgb(45, 45, 48);
                this.ForeColor = Color.White;
                this.TopMost = true;

                // 创建标题栏
                Panel titleBar = new Panel
                {
                    Height = 30,
                    Dock = DockStyle.Top,
                    BackColor = Color.FromArgb(35, 35, 38)
                };

                // 创建标题标签
                Label titleLabel = new Label
                {
                    Text = "正在保存设置",
                    Dock = DockStyle.Fill,
                    TextAlign = ContentAlignment.MiddleCenter,
                    Font = new Font("微软雅黑", 10, FontStyle.Bold),
                    ForeColor = Color.White
                };

                // 创建进度条
                progressBar = new ProgressBar
                {
                    Minimum = 0,
                    Maximum = 100,
                    Value = 0,
                    Size = new Size(360, 23),
                    Location = new Point(20, 50),
                    Style = ProgressBarStyle.Continuous
                };

                // 创建状态标签
                statusLabel = new Label
                {
                    AutoSize = false,
                    Size = new Size(360, 20),
                    Location = new Point(20, 80),
                    TextAlign = ContentAlignment.MiddleCenter,
                    Font = new Font("微软雅黑", 9),
                    ForeColor = Color.White
                };

                // 添加控件
                titleBar.Controls.Add(titleLabel);
                this.Controls.AddRange(new Control[] { titleBar, progressBar, statusLabel });

                // 添加拖动功能
                titleBar.MouseDown += (s, e) =>
                {
                    if (e.Button == MouseButtons.Left)
                    {
                        this.Capture = false;
                        const int WM_NCLBUTTONDOWN = 0xA1;
                        const int HTCAPTION = 0x2;
                        Message msg = Message.Create(this.Handle, WM_NCLBUTTONDOWN, new IntPtr(HTCAPTION), IntPtr.Zero);
                        this.DefWndProc(ref msg);
                    }
                };
            }

            public void UpdateProgress(int value, string status)
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(new Action(() => UpdateProgress(value, status)));
                    return;
                }

                progressBar.Value = Math.Min(100, Math.Max(0, value));
                statusLabel.Text = status;
                Application.DoEvents();
            }
        }

        // 修改保存按钮点击事件
        private async void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateInputs()) return;

            NetworkAdapterInfo selectedAdapterInfo = null;
            string selectedAdapter = null;

            // 在主线程中获取选中的适配器信息
            SafeInvoke(() =>
            {
                if (comboBoxAdapters.SelectedItem == null)
                {
                    MessageBox.Show("请选择网络适配器", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                selectedAdapterInfo = (NetworkAdapterInfo)comboBoxAdapters.SelectedItem;
                selectedAdapter = selectedAdapterInfo.Name;
            });

            if (selectedAdapter == null) return;

            try
            {
                // 创建并显示进度条窗体
                SafeInvoke(() =>
                {
                    progressForm = new ProgressForm();
                    progressForm.Show(this);
                });

                // 获取网络适配器
                NetworkInterface adapter = null;
                try
                {
                    SafeInvoke(() => progressForm.UpdateProgress(10, "正在获取网络适配器信息..."));
                    adapter = await Task.Run(() => NetworkInterface.GetAllNetworkInterfaces()
                        .FirstOrDefault(nic => nic.Name == selectedAdapter));

                    if (adapter == null)
                    {
                        throw new Exception($"无法找到网络适配器: {selectedAdapter}");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception($"获取网络适配器信息时出错: {ex.Message}");
                }

                bool ipChanged = false;
                bool dnsChanged = false;
                SafeInvoke(() =>
                {
                    ipChanged = HasIPChanged();
                    dnsChanged = HasDNSChanged();
                });

                StringBuilder statusMessage = new StringBuilder();

                if (ipChanged)
                {
                    SafeInvoke(() => progressForm.UpdateProgress(30, "正在设置IP地址..."));
                    bool isAutoIP = false;
                    string ip = "", subnet = "", gateway = "";

                    SafeInvoke(() =>
                    {
                        isAutoIP = chkAutoIP.Checked;
                        ip = txtIP.Text;
                        subnet = txtSubnetMask.Text;
                        gateway = txtGateway.Text;
                    });

                    if (!isAutoIP)
                    {
                        try
                        {
                            await Task.Run(() => SetStaticIP(ip, subnet, gateway));
                            statusMessage.AppendLine("IP已设置为静态地址");
                        }
                        catch (Exception ex)
                        {
                            SafeInvoke(() => progressForm.UpdateProgress(40, "正在使用备用方法设置IP..."));
                            await Task.Run(() => SetStaticIPAlternative(ip, subnet, gateway));
                            statusMessage.AppendLine("IP已设置为静态地址（使用备用方法）");
                        }
                    }
                    else
                    {
                        await Task.Run(() => SetDynamicIP());
                        statusMessage.AppendLine("IP已设置为自动获取");
                    }
                }

                if (dnsChanged)
                {
                    SafeInvoke(() => progressForm.UpdateProgress(60, "正在设置DNS..."));
                    bool isAutoDNS = false;
                    string primaryDNS = "", secondaryDNS = "";

                    SafeInvoke(() =>
                    {
                        isAutoDNS = chkAutoDNS.Checked;
                        primaryDNS = txtPrimaryDNS.Text;
                        secondaryDNS = txtSecondaryDNS.Text;
                    });

                    if (!isAutoDNS)
                    {
                        await Task.Run(() => SetStaticDNS(primaryDNS, secondaryDNS));
                        statusMessage.AppendLine("DNS已设置为静态地址");
                    }
                    else
                    {
                        await Task.Run(() => SetDynamicDNS());
                        statusMessage.AppendLine("DNS已设置为自动获取");
                    }
                }

                SafeInvoke(() => progressForm.UpdateProgress(80, "正在刷新网络设置..."));
                await Task.Run(() => RefreshNetworkAdapter(selectedAdapter));

                SafeInvoke(() => progressForm.UpdateProgress(90, "正在验证设置..."));
                await Task.Run(() => 
                {
                    try
                    {
                        LoadCurrentNetworkSettings();
                    }
                    catch (Exception ex)
                    {
                        SafeInvoke(() =>
                        {
                            MessageBox.Show($"验证设置时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        });
                    }
                });

                SafeInvoke(() =>
                {
                    progressForm.UpdateProgress(100, "设置保存完成！");
                    // 关闭进度条窗体
                    if (progressForm != null && !progressForm.IsDisposed)
                    {
                        progressForm.Close();
                        progressForm.Dispose();
                        progressForm = null;
                    }

                    // 显示成功动画
                    isGlowing = true;
                    animationTimer.Start();

                    // 显示最终的保存结果
                    MessageBox.Show($"设置已保存！\n\n{statusMessage}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                });
            }
            catch (Exception ex)
            {
                SafeInvoke(() =>
                {
                    // 关闭进度条窗体
                    if (progressForm != null && !progressForm.IsDisposed)
                    {
                        progressForm.Close();
                        progressForm.Dispose();
                        progressForm = null;
                    }

                    string errorMessage = ex.Message;
                    if (errorMessage.Contains("拒绝访问") || errorMessage.Contains("Access denied"))
                    {
                        errorMessage = "程序需要管理员权限才能修改网络设置。\n请右键点击程序，选择\"以管理员身份运行\"。";
                    }
                    MessageBox.Show($"保存设置时出错：{errorMessage}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                });
            }
        }

        // 修改网络适配器选择改变事件
        private void comboBoxAdapters_SelectedIndexChanged(object sender, EventArgs e)
        {
            SafeInvoke(() =>
            {
                if (comboBoxAdapters.SelectedItem is NetworkAdapterInfo adapterInfo)
                {
                    txtIP.Text = adapterInfo.IPAddress;
                    txtGateway.Text = adapterInfo.Gateway;
                    chkAutoIP.Checked = adapterInfo.IsDHCPEnabled;
                    chkAutoDNS.Checked = adapterInfo.IsDNSDHCPEnabled;
                    // 你可以继续填充子网掩码、DNS等
                }
            });
        }

        // 加载当前网络设置
        private void LoadCurrentNetworkSettings()
        {
            NetworkAdapterInfo selectedAdapterInfo = null;
            SafeInvoke(() =>
            {
                if (comboBoxAdapters.SelectedItem == null) return;
                selectedAdapterInfo = (NetworkAdapterInfo)comboBoxAdapters.SelectedItem;
            });

            if (selectedAdapterInfo == null) return;

            try
            {
                // 使用 netsh 命令获取详细的网络配置信息
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "netsh",
                        Arguments = $"interface ip show config \"{selectedAdapterInfo.Name}\"",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };
                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                // 解析输出内容
                var lines = output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                bool isIPDHCPEnabled = false;
                bool isDNSDHCPEnabled = false;
                string ipAddress = "";
                string subnetMask = "";
                string gateway = "";
                string primaryDNS = "";
                string secondaryDNS = "";

                foreach (var line in lines)
                {
                    var trimmedLine = line.Trim();
                    if (trimmedLine.Contains("DHCP enabled:") || trimmedLine.Contains("DHCP 已启用:"))
                    {
                        isIPDHCPEnabled = trimmedLine.Contains("Yes") || trimmedLine.Contains("是");
                    }
                    else if (trimmedLine.Contains("IP Address:") || trimmedLine.Contains("IP 地址:"))
                    {
                        var match = Regex.Match(trimmedLine, @"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})");
                        if (match.Success)
                        {
                            ipAddress = match.Groups[1].Value;
                        }
                    }
                    else if (trimmedLine.Contains("Subnet Prefix:") || trimmedLine.Contains("子网前缀:"))
                    {
                        var match = Regex.Match(trimmedLine, @"\((.*\s)(\d{1,3}(\.\d{1,3}){3})\)");
                        if (match.Success)
                        {
                            subnetMask = match.Groups[2].Value;
                        }
                        else
                        {
                            match = Regex.Match(trimmedLine, @"/(\d{1,2})(?:\s|$)");
                            if (match.Success)
                            {
                                subnetMask = ConvertCIDRToSubnetMask(match.Groups[1].Value);
                            }
                        }
                    }
                    else if (trimmedLine.Contains("Default Gateway:") || trimmedLine.Contains("默认网关:"))
                    {
                        var match = Regex.Match(trimmedLine, @"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})");
                        if (match.Success)
                        {
                            gateway = match.Groups[1].Value;
                        }
                    }
                    else if (trimmedLine.Contains("DNS servers configured through DHCP:") || trimmedLine.Contains("通过 DHCP 配置的 DNS 服务器:"))
                    {
                        isDNSDHCPEnabled = trimmedLine.Contains("Yes") || trimmedLine.Contains("是");
                    }
                    else if (trimmedLine.Contains("DNS Servers:") || trimmedLine.Contains("DNS 服务器:"))
                    {
                        var matches = Regex.Matches(trimmedLine, @"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})");
                        if (matches.Count > 0)
                        {
                            primaryDNS = matches[0].Value;
                            if (matches.Count > 1)
                            {
                                secondaryDNS = matches[1].Value;
                            }
                        }
                    }
                }

                // 更新缓存中的适配器信息
                if (cachedAdapters != null)
                {
                    var adapter = cachedAdapters.FirstOrDefault(a => a.Name == selectedAdapterInfo.Name);
                    if (adapter != null)
                    {
                        adapter.IPAddress = ipAddress;
                        adapter.Gateway = gateway;
                        adapter.IsDHCPEnabled = isIPDHCPEnabled;
                        adapter.IsDNSDHCPEnabled = isDNSDHCPEnabled;
                    }
                }

                // 在主线程中更新UI
                SafeInvoke(() =>
                {
                    // 保存原始值
                    originalIP = ipAddress;
                    originalGateway = gateway;
                    originalSubnetMask = subnetMask;
                    originalPrimaryDNS = primaryDNS;
                    originalSecondaryDNS = secondaryDNS;

                    // 更新显示
                    txtIP.Text = originalIP;
                    txtGateway.Text = originalGateway;
                    txtSubnetMask.Text = originalSubnetMask;
                    txtPrimaryDNS.Text = originalPrimaryDNS;
                    txtSecondaryDNS.Text = originalSecondaryDNS;

                    // 设置是否自动获取
                    chkAutoIP.Checked = isIPDHCPEnabled;
                    chkAutoDNS.Checked = isDNSDHCPEnabled;

                    // 根据是否自动获取来启用/禁用输入框
                    ToggleIPControls();
                    ToggleDNSControls();

                    // 重置保存按钮状态
                    btnSave.Enabled = false;
                });
            }
            catch (Exception ex)
            {
                SafeInvoke(() =>
                {
                    MessageBox.Show($"加载网络设置时出错：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                });
            }
        }

        // 当 IP 获取模式改变时切换输入框状态
        private void chkAutoIP_CheckedChanged(object sender, EventArgs e)
        {
            ToggleIPControls();
            CheckForChanges();
        }

        private void ToggleIPControls()
        {
            bool isAutoIP = chkAutoIP.Checked;
            txtIP.Enabled = !isAutoIP;
            txtGateway.Enabled = !isAutoIP;
            txtSubnetMask.Enabled = !isAutoIP;

            //if (isAutoIP)
            //{
            //    txtIP.Text = string.Empty;
            //    txtGateway.Text = string.Empty;
            //    txtSubnetMask.Text = string.Empty;
            //}
        }

        // 当 DNS 获取模式改变时切换输入框状态
        private void chkAutoDNS_CheckedChanged(object sender, EventArgs e)
        {
            ToggleDNSControls();
            CheckForChanges();
        }

        private void ToggleDNSControls()
        {
            bool isAutoDNS = chkAutoDNS.Checked;
            txtPrimaryDNS.Enabled = !isAutoDNS;
            txtSecondaryDNS.Enabled = !isAutoDNS;

            //if (isAutoDNS)
            //{
            //    txtPrimaryDNS.Text = string.Empty;
            //    txtSecondaryDNS.Text = string.Empty;
            //}
        }

        // 检查输入值是否发生变化
        private void CheckForChanges()
        {
            if (isInitializing) return;

            // 检查IP设置是否发生变化
            bool ipChanged = HasIPChanged();
            
            // 检查DNS设置是否发生变化
            bool dnsChanged = HasDNSChanged();

            // 只有在IP或DNS设置有任何变化时才启用保存按钮
            btnSave.Enabled = ipChanged || dnsChanged;

            // 可选：添加调试信息
            if (btnSave.Enabled)
            {
                string changeInfo = "";
                if (ipChanged) changeInfo += "IP设置已修改 ";
                if (dnsChanged) changeInfo += "DNS设置已修改";
                // 如果需要，可以在这里添加状态提示
                // statusLabel.Text = changeInfo;
            }
        }

        // 检查IP设置是否发生变化
        private bool HasIPChanged()
        {
            // 检查是否从静态切换到自动获取，或从自动获取切换到静态
            bool modeChanged = chkAutoIP.Checked != (string.IsNullOrEmpty(originalIP) && 
                                                   string.IsNullOrEmpty(originalGateway) && 
                                                   string.IsNullOrEmpty(originalSubnetMask));

            if (modeChanged)
            {
                return true;
            }

            // 如果模式没有改变，检查具体值的变化
            if (!chkAutoIP.Checked) // 静态IP模式
            {
                // 检查IP地址是否发生变化
                if (txtIP.Text != originalIP)
                {
                    return true;
                }

                // 检查网关是否发生变化
                if (txtGateway.Text != originalGateway)
                {
                    return true;
                }

                // 检查子网掩码是否发生变化
                if (txtSubnetMask.Text != originalSubnetMask)
                {
                    return true;
                }
            }

            // 如果没有检测到任何变化，返回false
            return false;
        }

        // 检查DNS设置是否发生变化
        private bool HasDNSChanged()
        {
            if (chkAutoDNS.Checked)
            {
                // 如果当前是自动获取，检查之前是否是静态DNS
                return !string.IsNullOrEmpty(originalPrimaryDNS) || 
                       !string.IsNullOrEmpty(originalSecondaryDNS);
            }
            else
            {
                // 如果当前是静态DNS，检查是否与原始值不同
                bool primaryDNSChanged = txtPrimaryDNS.Text != originalPrimaryDNS;
                bool secondaryDNSChanged = txtSecondaryDNS.Text != originalSecondaryDNS;

                // 只有当至少有一个值发生变化时才返回true
                return primaryDNSChanged || secondaryDNSChanged;
            }
        }

        // 将CIDR转换为子网掩码
        private string ConvertCIDRToSubnetMask(string cidr)
        {
            try
            {
                int bits = int.Parse(cidr.Replace("/", ""));
                if (bits < 0 || bits > 32) return "255.255.255.0";

                uint mask = ~((1u << (32 - bits)) - 1);
                return $"{mask >> 24}.{(mask >> 16) & 0xFF}.{(mask >> 8) & 0xFF}.{mask & 0xFF}";
            }
            catch
            {
                return "255.255.255.0";
            }
        }

        // 修改 SetStaticIP 方法
        private void SetStaticIP(string ipAddress, string subnetMask, string gateway)
        {
            string adapterName = null;
            SafeInvoke(() =>
            {
                if (comboBoxAdapters.SelectedItem == null)
                {
                    throw new Exception("未选择网络适配器");
                }
                adapterName = ((NetworkAdapterInfo)comboBoxAdapters.SelectedItem).Name;
            });

            if (string.IsNullOrEmpty(adapterName))
            {
                throw new Exception("无法获取网络适配器名称");
            }

            try
            {
                string fullSubnetMask = subnetMask.Contains(".") ? subnetMask : ConvertCIDRToSubnetMask(subnetMask);

                // 使用完整的命令路径
                string netshPath = @"C:\Windows\System32\netsh.exe";

                // 构建完整的命令
                string command = $"interface ip set address name=\"{adapterName}\" static {ipAddress} {fullSubnetMask} {gateway}";

                // 使用 ProcessStartInfo 的完整配置
                var startInfo = new ProcessStartInfo
                {
                    FileName = netshPath,
                    Arguments = command,
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardError = true,
                    RedirectStandardOutput = true
                };

                using (var process = new Process { StartInfo = startInfo })
                {
                    process.Start();
                    string output = process.StandardOutput.ReadToEnd();
                    string error = process.StandardError.ReadToEnd();
                    process.WaitForExit();

                    if (process.ExitCode != 0)
                    {
                        // 尝试使用备用命令
                        command = $"interface ipv4 set address name=\"{adapterName}\" static {ipAddress} {fullSubnetMask} {gateway}";
                        startInfo.Arguments = command;

                        using (var retryProcess = new Process { StartInfo = startInfo })
                        {
                            retryProcess.Start();
                            output = retryProcess.StandardOutput.ReadToEnd();
                            error = retryProcess.StandardError.ReadToEnd();
                            retryProcess.WaitForExit();

                            if (retryProcess.ExitCode != 0)
                            {
                                throw new Exception($"设置静态IP失败\n命令: {command}\n输出: {output}\n错误: {error}");
                            }
                        }
                    }
                }

                // 刷新网络适配器
                RefreshNetworkAdapter(adapterName);
            }
            catch (Exception ex)
            {
                throw new Exception($"设置静态 IP 失败: {ex.Message}");
            }
        }

        // 修改 SetStaticIPAlternative 方法
        private void SetStaticIPAlternative(string ipAddress, string subnetMask, string gateway)
        {
            string adapterName = null;
            SafeInvoke(() =>
            {
                if (comboBoxAdapters.SelectedItem == null)
                {
                    throw new Exception("未选择网络适配器");
                }
                adapterName = ((NetworkAdapterInfo)comboBoxAdapters.SelectedItem).Name;
            });

            if (string.IsNullOrEmpty(adapterName))
            {
                throw new Exception("无法获取网络适配器名称");
            }

            try
            {
                string fullSubnetMask = subnetMask.Contains(".") ? subnetMask : ConvertCIDRToSubnetMask(subnetMask);

                // 使用 cmd.exe 执行命令
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = $"/c netsh interface ip set address \"{adapterName}\" static {ipAddress} {fullSubnetMask} {gateway}",
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true
                    }
                };

                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                string error = process.StandardError.ReadToEnd();
                process.WaitForExit();

                // 检查输出中是否包含成功信息或错误代码
                if (process.ExitCode != 0 &&
                    !output.Contains("已在此接口上设置静态 IP") &&
                    !output.Contains("Static IP address is already set on this interface"))
                {
                    throw new Exception($"设置静态IP失败\n命令: netsh interface ip set address \"{adapterName}\" static {ipAddress} {fullSubnetMask} {gateway}\n输出: {output}\n错误: {error}");
                }

                // 等待一段时间让设置生效
                System.Threading.Thread.Sleep(2000);

                // 刷新网络适配器
                RefreshNetworkAdapter(adapterName);
            }
            catch (Exception ex)
            {
                throw new Exception($"备用方法设置静态IP失败: {ex.Message}");
            }
        }

        // 修改 SetDynamicIP 方法
        private void SetDynamicIP()
        {
            string selectedAdapter = null;
            SafeInvoke(() =>
            {
                if (comboBoxAdapters.SelectedItem == null)
                {
                    throw new Exception("未选择网络适配器");
                }
                selectedAdapter = ((NetworkAdapterInfo)comboBoxAdapters.SelectedItem).Name;
            });

            if (string.IsNullOrEmpty(selectedAdapter))
            {
                throw new Exception("无法获取网络适配器名称");
            }

            try
            {
                // 设置DHCP
                var dhcpProcess = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = $"/c netsh interface ip set address \"{selectedAdapter}\" dhcp",
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true
                    }
                };

                dhcpProcess.Start();
                string output = dhcpProcess.StandardOutput.ReadToEnd();
                string error = dhcpProcess.StandardError.ReadToEnd();
                dhcpProcess.WaitForExit();

                // 检查输出中是否包含成功信息
                bool success = output.Contains("已在此接口上启用 DHCP") ||
                             output.Contains("DHCP is already enabled on this interface") ||
                             dhcpProcess.ExitCode == 0;

                if (!success)
                {
                    // 如果第一个命令失败，尝试使用备用命令
                    dhcpProcess = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName = "cmd.exe",
                            Arguments = $"/c netsh interface ipv4 set address \"{selectedAdapter}\" dhcp",
                            CreateNoWindow = true,
                            UseShellExecute = false,
                            RedirectStandardOutput = true,
                            RedirectStandardError = true
                        }
                    };

                    dhcpProcess.Start();
                    output = dhcpProcess.StandardOutput.ReadToEnd();
                    error = dhcpProcess.StandardError.ReadToEnd();
                    dhcpProcess.WaitForExit();

                    success = output.Contains("已在此接口上启用 DHCP") ||
                             output.Contains("DHCP is already enabled on this interface") ||
                             dhcpProcess.ExitCode == 0;

                    if (!success)
                    {
                        throw new Exception($"设置DHCP失败\n输出: {output}\n错误: {error}");
                    }
                }

                // 等待一段时间让设置生效
                System.Threading.Thread.Sleep(2000);

                // 刷新网络适配器
                RefreshNetworkAdapter(selectedAdapter);
            }
            catch (Exception ex)
            {
                throw new Exception($"设置动态 IP 失败: {ex.Message}");
            }
        }

        private void VerifyDHCPEnabled(string adapterName)
        {
            try
            {
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = $"/c netsh interface ip show config \"{adapterName}\"",
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardOutput = true
                    }
                };

                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                bool dhcpEnabled = output.Contains("DHCP enabled: Yes") ||
                                  output.Contains("DHCP 已启用: 是") ||
                                  output.Contains("DHCP enabled: 是") ||
                                  output.Contains("已在此接口上启用 DHCP");

                if (!dhcpEnabled)
                {
                    throw new Exception("DHCP设置未成功应用");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"验证DHCP设置失败: {ex.Message}");
            }
        }

        // 设置静态 DNS
        private void SetStaticDNS(string primaryDNS, string secondaryDNS)
        {
            try
            {
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "netsh",
                        Arguments = $"interface ip add dns name=\"{comboBoxAdapters.SelectedValue}\" " + primaryDNS,
                        CreateNoWindow = true,
                        UseShellExecute = true,
                        Verb = "runas",
                        WindowStyle = ProcessWindowStyle.Hidden
                    }
                };

                process.Start();
                process.WaitForExit();
                if (!string.IsNullOrEmpty(secondaryDNS))
                {
                    process = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName = "netsh",
                            Arguments = $"interface ip add dns name=\"{comboBoxAdapters.SelectedValue}\" {secondaryDNS} index=2",
                            CreateNoWindow = true,
                            UseShellExecute = true,
                            Verb = "runas",
                            WindowStyle = ProcessWindowStyle.Hidden
                        }
                    };

                    process.Start();
                    process.WaitForExit();
                }

                // 刷新网络适配器
                RefreshNetworkAdapter(comboBoxAdapters.SelectedValue.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception($"设置静态 DNS 失败: {ex.Message}");
            }
        }

        // 设置动态 DNS
        private void SetDynamicDNS()
        {
            try
            {
                string adapterName = comboBoxAdapters.SelectedItem.ToString();
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = @"C:\Windows\System32\netsh.exe",
                        Arguments = $"interface ip set dns name=\"{adapterName}\" source=dhcp",
                        CreateNoWindow = true,
                        UseShellExecute = true,
                        Verb = "runas",
                        WindowStyle = ProcessWindowStyle.Hidden
                    }
                };

                process.Start();
                process.WaitForExit();

                if (process.ExitCode != 0)
                {
                    throw new Exception($"设置动态DNS失败，错误代码: {process.ExitCode}");
                }

                // 刷新DNS缓存
                process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = @"C:\Windows\System32\ipconfig.exe",
                        Arguments = "/flushdns",
                        CreateNoWindow = true,
                        UseShellExecute = true,
                        Verb = "runas",
                        WindowStyle = ProcessWindowStyle.Hidden
                    }
                };

                process.Start();
                process.WaitForExit();

                // 刷新网络适配器
                RefreshNetworkAdapter(adapterName);
            }
            catch (Exception ex)
            {
                throw new Exception($"设置动态 DNS 失败: {ex.Message}");
            }
        }

        // 检查当前休眠状态
        private void CheckCurrentSleepState()
        {
            try
            {
                // 获取当前休眠设置
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = "/c powercfg /query SCHEME_CURRENT SUB_SLEEP && powercfg /query SCHEME_CURRENT SUB_VIDEO",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };
                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                // 解析当前休眠超时设置
                var lines = output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                bool standbyDisabled = false;
                bool monitorDisabled = false;

                foreach (var line in lines)
                {
                    if (line.Contains("Standby timeout"))
                    {
                        var match = Regex.Match(line, @"(\d+)");
                        if (match.Success)
                        {
                            originalStandbyTimeout = match.Groups[1].Value;
                            standbyDisabled = originalStandbyTimeout == "0";
                        }
                    }
                    else if (line.Contains("Video timeout"))
                    {
                        var match = Regex.Match(line, @"(\d+)");
                        if (match.Success)
                        {
                            originalMonitorTimeout = match.Groups[1].Value;
                            monitorDisabled = originalMonitorTimeout == "0";
                        }
                    }
                }

                // 检查快速启动状态
                process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = "/c powercfg /h",
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
                };
                process.Start();
                output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                bool hibernateDisabled = output.Contains("Hibernate: Off");

                // 如果所有相关设置都被禁用，则认为休眠已被禁用
                isSleepPrevented = standbyDisabled && monitorDisabled && hibernateDisabled;

                // 在主线程中更新UI
                SafeInvoke(() =>
                {
                    chkPreventSleep.Checked = isSleepPrevented;
                });
            }
            catch (Exception ex)
            {
                // 如果无法获取状态，使用默认值
                isSleepPrevented = false;
                SafeInvoke(() =>
                {
                    chkPreventSleep.Checked = false;
                    MessageBox.Show($"检查休眠状态时出错：{ex.Message}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                });
            }
        }

        // 控制休眠状态
        private void chkPreventSleep_CheckedChanged(object sender, EventArgs e)
        {
            if (isInitializing) return;

            try
            {
                if (chkPreventSleep.Checked)
                {
                    // 使用 Windows API 防止系统休眠
                    SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS |
                                          EXECUTION_STATE.ES_SYSTEM_REQUIRED |
                                          EXECUTION_STATE.ES_DISPLAY_REQUIRED);

                    // 使用单个进程执行所有 powercfg 命令
                    var process = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName = "cmd.exe",
                            Arguments = "/c powercfg /change standby-timeout-ac 0 && " +
                                      "powercfg /change monitor-timeout-ac 0 && " +
                                      "powercfg /hibernate off && " +
                                      "powercfg /h off",
                            UseShellExecute = true,
                            CreateNoWindow = true,
                            Verb = "runas"
                        }
                    };
                    process.Start();
                    process.WaitForExit();

                    isSleepPrevented = true;
                    MessageBox.Show("已禁用系统休眠", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    keepAliveTimer.Start();
                }
                else
                {
                    // 恢复系统休眠
                    SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);

                    // 使用单个进程执行所有 powercfg 命令
                    var process = new Process
                    {
                        StartInfo = new ProcessStartInfo
                        {
                            FileName = "cmd.exe",
                            Arguments = $"/c powercfg /change standby-timeout-ac {originalStandbyTimeout} && " +
                                      $"powercfg /change monitor-timeout-ac {originalMonitorTimeout} && " +
                                      "powercfg /hibernate on && " +
                                      "powercfg /h on",
                            UseShellExecute = true,
                            CreateNoWindow = true,
                            Verb = "runas"
                        }
                    };
                    process.Start();
                    process.WaitForExit();

                    isSleepPrevented = false;
                    MessageBox.Show($"已恢复系统休眠设置\n休眠时间：{originalStandbyTimeout}分钟\n显示器关闭时间：{originalMonitorTimeout}分钟",
                        "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    keepAliveTimer.Stop();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"设置休眠状态时出错：{ex.Message}\n请确保以管理员身份运行程序。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                chkPreventSleep.Checked = isSleepPrevented; // 恢复复选框状态
            }
        }

        private void InitializeKeepAliveTimer()
        {
            if (keepAliveTimer == null)
            {
                keepAliveTimer = new System.Windows.Forms.Timer();
                keepAliveTimer.Interval = 60000; // 每分钟执行一次
                keepAliveTimer.Tick += KeepAliveTimer_Tick;
            }
        }

        private void KeepAliveTimer_Tick(object sender, EventArgs e)
        {
            if (isSleepPrevented)
            {
                SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS |
                                      EXECUTION_STATE.ES_SYSTEM_REQUIRED |
                                      EXECUTION_STATE.ES_DISPLAY_REQUIRED);
            }
        }

        // 验证所有输入
        private bool ValidateInputs()
        {
            if (!chkAutoIP.Checked)
            {
                if (string.IsNullOrEmpty(txtIP.Text))
                {
                    MessageBox.Show("请输入IP地址", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
                if (string.IsNullOrEmpty(txtSubnetMask.Text))
                {
                    MessageBox.Show("请输入子网掩码", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return false;
                }
                //if (string.IsNullOrEmpty(txtGateway.Text))
                //{
                //    MessageBox.Show("请输入默认网关", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //    return false;
                //}
            }

            // 只有在手动设置DNS且DNS发生变化时才验证
            if (!chkAutoDNS.Checked && HasDNSChanged() && string.IsNullOrEmpty(txtPrimaryDNS.Text))
            {
                MessageBox.Show("请输入首选DNS服务器", "错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }

            return true;
        }

        // 刷新网络适配器
        private void RefreshNetworkAdapter(string adapterName)
        {
            try
            {
                // 禁用网络适配器
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = $"/c netsh interface set interface \"{adapterName}\" admin=disable",
                        CreateNoWindow = true,
                        UseShellExecute = true,
                        Verb = "runas",
                        WindowStyle = ProcessWindowStyle.Hidden
                    }
                };

                process.Start();
                process.WaitForExit();

                System.Threading.Thread.Sleep(1000);

                // 启用网络适配器
                process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = $"/c netsh interface set interface \"{adapterName}\" admin=enable",
                        CreateNoWindow = true,
                        UseShellExecute = true,
                        Verb = "runas",
                        WindowStyle = ProcessWindowStyle.Hidden
                    }
                };

                process.Start();
                process.WaitForExit();

                System.Threading.Thread.Sleep(2000);

                // 刷新DNS缓存
                process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = "/c ipconfig /flushdns",
                        CreateNoWindow = true,
                        UseShellExecute = true,
                        Verb = "runas",
                        WindowStyle = ProcessWindowStyle.Hidden
                    }
                };

                process.Start();
                process.WaitForExit();
            }
            catch (Exception ex)
            {
                throw new Exception($"刷新网络适配器失败: {ex.Message}");
            }
        }

        // 验证IP设置是否生效
        private void VerifyIPSettings(string adapterName, string expectedIP, string expectedSubnet, string expectedGateway)
        {
            try
            {
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "cmd.exe",
                        Arguments = $"/c netsh interface ip show config \"{adapterName}\"",
                        CreateNoWindow = true,
                        UseShellExecute = false,
                        RedirectStandardOutput = true
                    }
                };

                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                // 检查IP地址
                if (!output.Contains(expectedIP) && !output.Contains(expectedSubnet))
                {
                    throw new Exception("IP地址设置未生效");
                }

                // 检查子网掩码
                string fullSubnetMask = expectedSubnet.Contains(".") ? expectedSubnet : ConvertCIDRToSubnetMask(expectedSubnet);
                if (!output.Contains($"Subnet Prefix: {fullSubnetMask}") &&
                    !output.Contains($"子网前缀: {fullSubnetMask}"))
                {
                    throw new Exception("子网掩码设置未生效");
                }

                // 检查网关
                if (!output.Contains($"Default Gateway: {expectedGateway}") &&
                    !output.Contains($"默认网关: {expectedGateway}"))
                {
                    throw new Exception("网关设置未生效");
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"验证IP设置失败: {ex.Message}");
            }
        }

        // 添加回 InputFields_TextChanged 方法
        private void InputFields_TextChanged(object sender, EventArgs e)
        {
            if (isInitializing) return;

            var textBox = sender as TextBox;
            if (textBox == null) return;

            // 验证IP地址格式
            if (textBox == txtIP || textBox == txtGateway || textBox == txtPrimaryDNS || textBox == txtSecondaryDNS || textBox == txtSubnetMask)
            {
                if (!string.IsNullOrEmpty(textBox.Text))
                {
                    if (!IsValidIPAddress(textBox.Text))
                    {
                        textBox.BackColor = System.Drawing.Color.LightPink;
                        btnSave.Enabled = false;
                        return;
                    }
                }
                textBox.BackColor = System.Drawing.SystemColors.Window;
            }

            // 当IP地址改变时，自动计算子网掩码
            if (textBox == txtIP && !chkAutoIP.Checked)
            {
                string subnetMask = CalculateSubnetMask(textBox.Text);
                if (!string.IsNullOrEmpty(subnetMask))
                {
                    txtSubnetMask.Text = subnetMask;
                }
            }

            CheckForChanges();
        }

        // 添加回 IsValidIPAddress 方法
        private bool IsValidIPAddress(string ip)
        {
            if (string.IsNullOrEmpty(ip)) return true;

            string pattern = @"^(\d{1,3}\.){3}\d{1,3}$";
            if (!Regex.IsMatch(ip, pattern)) return false;

            string[] parts = ip.Split('.');
            foreach (string part in parts)
            {
                if (int.Parse(part) > 255) return false;
            }

            return true;
        }

        // 计算子网掩码
        private string CalculateSubnetMask(string ipAddress)
        {
            if (string.IsNullOrEmpty(ipAddress)) return "255.255.255.0";

            string[] parts = ipAddress.Split('.');
            if (parts.Length != 4) return "255.255.255.0";

            try
            {
                int firstOctet = int.Parse(parts[0]);
                int secondOctet = int.Parse(parts[1]);

                // 根据IP地址类别返回默认子网掩码
                if (firstOctet >= 1 && firstOctet <= 126)
                {
                    return "255.0.0.0"; // A类
                }
                else if (firstOctet >= 128 && firstOctet <= 191)
                {
                    return "255.255.0.0"; // B类
                }
                else if (firstOctet >= 192 && firstOctet <= 223)
                {
                    return "255.255.255.0"; // C类
                }
                else if (firstOctet >= 224 && firstOctet <= 239)
                {
                    return "255.0.0.0"; // D类
                }
                else if (firstOctet >= 240 && firstOctet <= 255)
                {
                    return "255.0.0.0"; // E类
                }
            }
            catch
            {
                // 如果解析失败，返回默认值
                return "255.255.255.0";
            }

            return "255.255.255.0";
        }
    }
}

